﻿using System.ComponentModel.Composition;
using System.ComponentModel.DataAnnotations;

namespace OperationPlugins.Validators.DataAnnotations
{
    [Export(typeof(IUsePluginValidatorsAttributeResolveBranch))]
    [DefaultPriority]
    internal sealed class DefaultIUsePluginValidatorsAttributeResolveBranch : IUsePluginValidatorsAttributeResolveBranch
    {
        /// <summary>
        /// Resolves the current branch.
        /// </summary>
        /// <remarks>
        /// The default value is <see cref="Branches.Any"/>.
        /// </remarks>
        /// <param name="value">The value to validate.</param>
        /// <param name="validationContext">Describes the context in which a data annotations validation check is performed.</param>
        /// <returns>The current branch.</returns>
        BranchId IUsePluginValidatorsAttributeResolveBranch.ResolveBranch(object value, ValidationContext validationContext)
        {
            BranchId branch = OperationPluginsContext.Current.CurrentActionBranch;

            if (branch == null)
            {
                var e = new ResolveBranchEventArgs(value, validationContext);

                DataAnnotationsValidationResourceResolver.OnResolveBranch(this, e);

                branch = e.Resolved;
            }

            return branch ?? (Branches.Any);
        }
    }
}
